struct ListNode {
    int val;
    ListNode* next;
    ListNode(int x) : val(x), next(nullptr) {}
};

class Solution {
public:
    bool hasCycle(ListNode* head) {
        if (head == nullptr || head->next == nullptr) {
            return false;
        }
        ListNode* tmp = head->next;
        while (tmp!=nullptr&&tmp->next!=nullptr) {
            if (head == tmp) {
                return true;
            }
            head = head->next;
            tmp = tmp->next->next;
        }
        return false;
    }
};